package integral

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"private-domain-overseas-service/app/business/api/internal/svc"
	"private-domain-overseas-service/pkg/common"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/hzintegralwalletrecord"
	"private-domain-overseas-service/tools/ent/predicate"
	"time"
)

type IntegralWalletRecordDao struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewIntegralWalletRecordDao(ctx context.Context, svcCtx *svc.ServiceContext) *IntegralWalletRecordDao {
	return &IntegralWalletRecordDao{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// ListIntegralWalletRecordByPage -根据条件分页查询积分记录
func (l *IntegralWalletRecordDao) ListIntegralWalletRecordByPage(cond []predicate.HzIntegralWalletRecord, current, pageSize int64) ([]*ent.HzIntegralWalletRecord, int, error) {

	//计算分页偏移量
	offset := common.Offset(current, pageSize)
	//执行查询
	integralWalletRecords, err := l.svcCtx.Orm.HzIntegralWalletRecord.Query().
		Where(cond...).
		Order(ent.Desc(hzintegralwalletrecord.FieldID)).
		Offset(int(offset)).
		Limit(int(pageSize)).
		All(l.ctx)
	if err != nil {
		return nil, 0, err
	}

	//查询总数
	count, err := l.svcCtx.Orm.HzIntegralWalletRecord.Query().
		Where(cond...).
		Count(l.ctx)
	if err != nil {
		return nil, 0, err
	}

	return integralWalletRecords, count, nil

}

// WalletRecordConditionsSumField  - 根据条件Sum指定字段的总数
func (l *IntegralWalletRecordDao) WalletRecordConditionsSumField(conditions []predicate.HzIntegralWalletRecord, field string) (int, error) {
	count, err := l.svcCtx.Orm.HzIntegralWalletRecord.Query().
		Where(conditions...).
		Aggregate(ent.Sum(field)).Int(l.ctx)
	if err != nil {
		return 0, err
	}
	return count, nil
}

// CreateIntegralWalletRecord -创建积分记录明细
func (l *IntegralWalletRecordDao) CreateIntegralWalletRecord(tx *ent.Tx, record *ent.HzIntegralWalletRecord) error {
	clientDao := l.svcCtx.Orm.HzIntegralWalletRecord
	if tx != nil {
		clientDao = tx.HzIntegralWalletRecord
	}
	_, err := clientDao.Create().
		SetUserID(record.UserID).
		SetIntegralWalletID(record.IntegralWalletID).
		SetRecordTitle(record.RecordTitle).
		SetRecordNumber(record.RecordNumber).
		SetRecordAmount(record.RecordAmount).
		SetRecordStatus(record.RecordStatus).
		SetRecordType(record.RecordType).
		SetRecordActiveBalance(record.RecordActiveBalance).
		SetRecordFreezeBalance(record.RecordFreezeBalance).
		SetCreatedAt(time.Now().Unix()).
		SetUpdateAt(time.Now().Unix()).
		Save(l.ctx)
	if err != nil {
		return err
	}
	return nil
}

// WalletRecordConditionsFirst - 根据条件查询单挑记录
func (l *IntegralWalletRecordDao) WalletRecordConditionsFirst(conditions []predicate.HzIntegralWalletRecord) (*ent.HzIntegralWalletRecord, error) {
	record, err := l.svcCtx.Orm.HzIntegralWalletRecord.Query().Where(conditions...).First(l.ctx)
	if err != nil {
		return nil, err
	}
	return record, nil

}
